#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <pmc.h>

#define COUNTER "p6-cpu-clk-unhalted"

void do_something (void)
{
	unsigned long long value;
	int i;

	for (i = value = 0; i < 100000; i++)
		value += i >> 2;

	fprintf (stdout, "do_something value = %llu\n", value);
}

int main (int argc, char *argv[])
{
	pmc_id_t p;
	const struct pmc_cpuinfo *info;
	unsigned long long value;

	if (pmc_init() < 0)
	{
		fprintf (stderr, "Failed to run pmc_init()\n");
		perror ("perror: ");
		return 0;
	}
	if (pmc_cpuinfo (&info) != 0)
	{
		fprintf (stderr, "Failed to run pmc_cpuinfo()\n");
		perror ("perror: ");
		return 0;
	}

	fprintf (stdout, "pmc_name_of_cputype(info->pm_cputype) = %s\n", pmc_name_of_cputype(info->pm_cputype));
	fprintf (stdout, "info->pm_ncpu = %d\n", info->pm_ncpu);
	fprintf (stdout, "info->pm_npmc = %d\n", info->pm_npmc);

	if (pmc_allocate (COUNTER, PMC_MODE_TC, 0, PMC_CPU_ANY, &p) < 0)
	{
		fprintf (stderr, "Failed to pmc_allocate!\n");
		perror ("perror: ");
		return 0;
	}

	if (pmc_start (p) < 0)
	{
		fprintf (stderr, "Failed to pmc_start!\n");
		return 0;
	}
 
	do_something();

	if (pmc_read (p, &value) < 0)
	{
		fprintf (stderr, "Failed to pmc_read\n");
		perror ("perror: ");
		return 0;
	}

	fprintf (stdout, "PMC counter returned: %llu\n", value);

	return 0;
}
